//判断一个单链表是否有环
// 要求时间复杂度o(n)  空间复杂度o(n)
// 空间复杂度o（1）则更好
function Node(val) {
    this.val = val;
    this.next = null;
}
var a = new Node(1);
var b = new Node(2);
var c = new Node(3);
var d = new Node(4);
a.next = b;
b.next = c;
c.next = d;
d.next = b;
var hasCycle = (head) =>{
    while(head) {
        if (head.flag) return true;
        head.flag = true;
        head = head.next;
    }
    return false;
}

//JSON.stringify()不能序列化含有循环引用的结构
var hasCycle = (head) =>{
    try{
        JSON.stringify(head);
        return false;
    }catch (e) {
        return true;
    }
}
//快慢指针
var hasCycle = (head) =>{
    if(!head || !head.next) return false;
    let fast = head.next.next;
    let slow = head;
    while (slow !== fast){
        if(!fast || !fast.next) return false;
        fast = fast.next.next;
        slow = slow.next;
    }
    return true;
}
console.log(hasCycle(a));
